'use strict';

/**
 * @ngdoc function
 * @name VOA.controllers:TopicsCtrl
 * @description
 * # TopicsCtrl
 * Topics Controller of the VOA app
 */

angular.module('VOA.controllers')
.controller('TopicsCtrl', function($scope, $rootScope, $stateParams, $ionicLoading, $ionicModal, $timeout, $state, $location, $log, Topics, Tabs) {
  $log.debug('topics ctrl', $stateParams);

  // before enter view event
  // $scope.$on('$ionicView.beforeEnter', function() {
  //   // track view
  //   if (window.analytics) {
  //     window.analytics.trackView('topics view');
  //   }
  // });

  $scope.currentTab = Topics.currentTab();

  // check if tab is changed
  if ($stateParams.tab !== Topics.currentTab()) {
    $scope.currentTab = Topics.currentTab($stateParams.tab);
    // reset data if tab is changed
    Topics.resetData();
  }

  $scope.topics = Topics.getTopics();

  // pagination

  $scope.loadError = false;
  $log.debug('page load, has next page ? ', $scope.hasNextPage);
  $scope.doRefresh = function() {
    Topics.currentTab($stateParams.tab);
    $log.debug('do refresh');
    Topics.refresh().promise.then(function(response) {
        $log.debug('do refresh complete');
        $scope.title=response.title;
        $scope.topics = response.itemArray;
        $scope.hasNextPage = true;
        $scope.loadError = false;
      }, $rootScope.requestErrorHandler({
        noBackdrop: true
      }, function() {
        $scope.loadError = true;
      })
    ).finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
 
  };
  $scope.doRefresh();
});
